﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows;
using System.IO;
using GameLib.WorldMap;

namespace Sandbox.Scene.Elements
{
	public class ReferenceImage
	{
		public ReferenceImage(MapScene scene, int index)
		{
			Scene = scene;
			Index = index;

			MapRefImageData data = Scene.Map.ReferenceImageData[Index];

			BitmapImage imageSource = new BitmapImage(new Uri(data.ImagePath, UriKind.Relative));
			Image = new Image();
			Image.Source = imageSource;
			Image.Stretch = Stretch.None;
			Image.Width = imageSource.PixelWidth;
			Image.Height = imageSource.PixelHeight;
			Image.Opacity = data.Opacity;
			Image.SetValue(Canvas.LeftProperty, data.X);
			Image.SetValue(Canvas.TopProperty, data.Y);
			Image.RenderTransform = new ScaleTransform(data.Scale, data.Scale);

			Canvas canvas = Scene.GetSceneObjectCanvas(MapSceneObjectLayers.ReferenceImages);
			canvas.Children.Add(Image);
		}

		public int Index
		{
			get;
			set;
		}

		public double Opacity
		{
			set 
			{
				Image.Opacity = value;
				MapRefImageData data = Scene.Map.ReferenceImageData[Index];
				data.Opacity = value;
				Scene.Map.ReferenceImageData[Index] = data;
			}

			get { return Scene.Map.ReferenceImageData[Index].Opacity; }
		}

		public string ImagePath
		{
			get { return Scene.Map.ReferenceImageData[Index].ImagePath; }
		}

		public void Scroll(double x, double y)
		{
			MapRefImageData data = Scene.Map.ReferenceImageData[Index];
			data.X += x / Scene.MapScale;
			data.Y += y / Scene.MapScale;
			Scene.Map.ReferenceImageData[Index] = data;
			Image.SetValue(Canvas.LeftProperty, data.X);
			Image.SetValue(Canvas.TopProperty, data.Y);
		}

		public void Scale(double delta)
		{
			MapRefImageData data = Scene.Map.ReferenceImageData[Index];
			data.Scale = Math.Max(data.Scale + delta, 0);
			Scene.Map.ReferenceImageData[Index] = data;
			Image.RenderTransform = new ScaleTransform(data.Scale, data.Scale);
		}

		public override string ToString()
		{
			return Path.GetFileNameWithoutExtension(ImagePath);
		}

		private MapScene Scene
		{
			get;
			set;
		}

		private Image Image
		{
			get;
			set;
		}
	}
}
